package org.lifxue.jqda.lucene.index.impl;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.SimpleFSDirectory;
import org.lifxue.jqda.lucene.index.Indexer;
import org.lifxue.jqda.util.GlobalConstant;
import org.lifxue.jqda.util.GlobalVar;
import org.wltea.analyzer.lucene.IKAnalyzer;

/**
 * 
 * @Description: 创建索引 Lucene 3.0+
 * @Author: zhangzuoqiang
 * @Date: Sep 26, 2011
 */
public class IndexerFile implements Indexer {

	private static Log logger = LogFactory.getLog(IndexerFile.class);
	// 保存索引文件的地方
	private String INDEXER_INDEX_DIR;

	public IndexerFile() {
		INDEXER_INDEX_DIR = GlobalVar.USER_HOME + GlobalVar.FILE_PATH_DELIMITER
				+ GlobalConstant.DEFAULT_CONFIG_DIR
				+ GlobalVar.FILE_PATH_DELIMITER + GlobalConstant.INDEX_DIR;
	}

	@Override
	public void indexer(List<String> dirs, List<String> types) {
		for (String s : dirs) {
			indexer(s, types);
		}
	}

	@Override
	public void indexer(String dir, List<String> types) {
		try {
			IndexWriter indexWriter = null;
			// 创建Directory对象
			Directory directory = new SimpleFSDirectory(new File(
					INDEXER_INDEX_DIR));
			Analyzer analyzer = new IKAnalyzer(); // 采用的分词器
			// 创建IndexWriter对象,第一个参数是Directory,第二个是分词器,第三个表示是否是创建,如果为false为在此基础上面修改,第四表示表示分词的最大值，比如说new
			// MaxFieldLength(2)，就表示两个字一分，一般用 IndexWriter.MaxFieldLength.LIMITED
			if (this.isEmpty()) {
				indexWriter = new IndexWriter(directory, analyzer, true,
						IndexWriter.MaxFieldLength.UNLIMITED);
				indexDocs(indexWriter, new File(dir), types);
			} else {
				indexWriter = new IndexWriter(directory, analyzer, false,
						IndexWriter.MaxFieldLength.UNLIMITED);
				indexDocs(indexWriter, new File(dir), types);
			}
			// 查看IndexWriter里面有多少个索引
			// logger.info("numDocs=" + indexWriter.numDocs());
			// indexWriter.optimize();//优化
			indexWriter.close();
		} catch (IOException ex) {
			logger.debug(ex);
		}
	}

	private void indexDocs(IndexWriter writer, File file, List<String> types)
			throws IOException {
		if (file.canRead()) {
			if (file.isDirectory()) {
				String[] files = file.list();
				if (files != null) {
					for (int i = 0; i < files.length; i++) {
						indexDocs(writer, new File(file, files[i]), types);
					}
				}
			} else {
				String name = file.getName();
				String ext = name.substring(name.lastIndexOf(".") + 1);
				if (types.contains(ext)) {
					try {
						writer.addDocument(FileDocument.Document(file, ext));
					} // at least on windows, some temporary files raise this
						// exception with an "access denied" message
						// checking if the file can be read doesn't help
					catch (FileNotFoundException fnfe) {
						logger.debug(fnfe);
					}
				}
			}
		}
	}

	@Override
	public boolean isEmpty() {
		boolean is = false;
		File file = new File(INDEXER_INDEX_DIR);

		if (file.isDirectory()) {
			String[] files = file.list();
			if (files == null) {
				is = true;
			} else {
				List<String> list = Arrays.asList(files);
				if (!list.contains("segments.gen")) {
					is = true;
				}
			}

		} else {
			is = true;
		}
		return is;
	}
	/**
	 * @param args
	 * @throws IOException
	 */
	// public static void main(String[] args) throws IOException {
	// GlobalVar.init();
	// String s = "E:\\Studys";
	// String s2 = "E:\\luecne-data-demo\\dateDir";
	// List<String> list = new ArrayList<String>();
	// list.add(s);
	// list.add(s2);
	// Indexer a = new IndexerFile();
	// a.indexer(list, new ArrayList<String>());
	//
	// }
}
